package com.hongshan.wallet.core .wallet

import android.app.Application
import android.databinding.ObservableField
import android.view.View
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.base.SingleLiveEvent
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch


/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.home
 * @author   : zhangxx
 * @date     : 2019/3/27
 * @email    : qq957413212@hotmail.com
 * @desc     : //TUDO
 */
class IntoBalanceViewModel(application: Application) : MyViewModel(application) {

    val money = ObservableField<String>()
    val maxMoney = ObservableField<String>("最多可转入${MyApplication.userInfo.get()?.commission_balance}元")
    val showPwdDialog = SingleLiveEvent<Unit>()
    val hidePwdDialog = SingleLiveEvent<Unit>()
    val showErrorDialog = SingleLiveEvent<Unit>()

    var click = View.OnClickListener {
        showPwdDialog.call()
    }

    private fun intoBalance() {
        GlobalScope.launch(Dispatchers.Main) {
            val net = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.intoBalance(money.get()!!).execute() }
            }
            val response = net.await()
            val result = response?.body()
            if (result?.code == 0) {
                hidePwdDialog.call()
                toast("转入成功")
                finish.call()
//                val userDescBean = MyApplication.userInfo.get()
//                userDescBean?.commission_balance =
//                    (userDescBean!!.commission_balance.toDouble() - money.get()!!.toDouble()).toString()
//                MyApplication.userInfo.set(userDescBean)
//                maxMoney.set("最多可转入${MyApplication.userInfo.get()?.commission_balance}元")
            }
        }
    }

    fun checkPwd(it: String) {
        val s = money.get()
        val doubleS = s?.toDouble()
        if (s == null || s.isEmpty() || doubleS!! > MyApplication.userInfo.get()!!.commission_balance.toDouble() || doubleS < 0) {
            toast("金额不正确")
            return
        }
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.checkPayPwd(it).execute() }
            }
            val response = result.await() ?: return@launch
            if (response.body()?.code == 0) {
                intoBalance()
            } else if (response.body()?.code == -1) {
                showErrorDialog.call()
            } else {
                toast(response.body()?.msg)
            }

        }
    }
}